package com.aaa.Dao;

import com.aaa.Entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ProductDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    private RowMapper<Product> rowMapper = new RowMapper<Product>() {
        public Product mapRow(ResultSet resultSet, int i) throws SQLException {
            Product product = new Product();
            product.setId(resultSet.getLong("id"));
            product.setName(resultSet.getString("name"));
            product.setPrice(resultSet.getDouble("price"));
            product.setDate(resultSet.getString("date"));
            product.setQuantity(resultSet.getInt("quantity"));
            return product;
        }
    };

    public List<Product> listAll(Integer offset,Integer limit){
        String sql ="select id,name,price,date,quantity from product limit ?,?";
        List<Product> query = jdbcTemplate.query(sql, rowMapper,offset,limit);
        return query;
    }

    public Integer count(){
        String sql = "select count(id) as c from product";
        Integer result = this.jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        });
        return  result;
    }


    public Integer Delete(Integer id){
        String sql = "delete from product where id=?";
        Integer update = jdbcTemplate.update(sql, id);
        return update;
    }

    public Integer Add(Product product){
        String sql = "insert into product(name,price,date,quantity)values(?,?,?,?)";
        int update = jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getDate(), product.getQuantity());
        return update;
    }

    public Integer Update(Product product){
        String sql= "update product set name=?,price=?,date=?,quantity=? where id=?";
        int update = jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getDate(), product.getQuantity(), product.getId());
        return update;
    }
}
